package com.uestc.shop.web;

import com.uestc.shop.domain.User;
import com.uestc.shop.domain.dto.ProductAddDto;
import com.uestc.shop.domain.dto.UserProfileDto;
import com.uestc.shop.service.IUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @Package: com.uestc.shop.web
 * @author: Jounghu
 * @date: 2018/7/26 1:29
 * @version: V1.0
 */
@Controller
public class PageController {


    @Autowired
    IUserService userService;

    @Autowired
    ModelMapper modelMapper;

    /**
     * 前往 首页
     *
     * @return
     */
    @GetMapping(value = {"/", "/index"})
    public String indexPage() {
        return "index";
    }


    /**
     * 前往登录页
     *
     * @return
     */
    @GetMapping("/login")
    public String loginPage() {
        return "Login";
    }


    /***
     * 前往注册页面
     * @return
     */
    @GetMapping("/reg")
    public String regPage() {
        return "register";
    }

    /***
     * 前往个人中心页面
     * @return
     */
    @GetMapping("/profile")
    public String profilePage(HttpServletRequest request) {
        String username = (String) request.getSession().getAttribute("user");
        if (StringUtils.isEmpty(username)) {
            // 没有登录
            return "redirect:/login";
        }

        User user = userService.findUserByName(username);
        if (user == null) {
            // 虚假用户
            request.getSession().removeAttribute("username");
            return "redirect:/login";
        }

        UserProfileDto userProfile = modelMapper.map(user, UserProfileDto.class);
        request.setAttribute("userprofile",userProfile);
        return "profile";
    }


    @GetMapping("/product")
    public String productAddPage(HttpServletRequest request){
        request.setAttribute("product",new ProductAddDto());
        return "product";
    }


}
